import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'

// 创建 axios 实例
const http = axios.create({
  baseURL: import.meta.env.ENV_BASE_URL,
  timeout: 60000,
})

// 请求拦截
const getRequestMap = new Map()
http.interceptors.request.use(
  function (config) {
    // 请求拦截逻辑
    return config
  },
  function (err) {
    return Promise.reject(err)
  },
)

// 响应拦截
http.interceptors.response.use(
  function (res) {
    console.log(res)

    getRequestMap.delete(res.config.url)
    if (res.status === 200) {
      if (res.data.code === 401) {
        return Promise.reject('No auth;')
      }
      if (res.data.code === 0) {
        return Promise.resolve(res.data.data)
      } else {
        let message = res.data.message || ''
        ElMessage.error('错误：' + message + '54545646')
        return Promise.reject(res.data)
      }
    }

    return Promise.reject(res)
  },
  function (err) {
    getRequestMap.delete(err.config ? err.config.url : '')
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求出错'
          break
        case 401:
          break
        case 403:
          err.message = '拒绝访问'
          break
        case 404:
          err.message = '请求错误,未找到该资源'
          break
        case 500:
          err.message = '服务器端出错'
          break
      }
    } else if ('ERR_CANCELED' === err.code) {
      return Promise.reject(err)
    } else {
      err.message = '连接服务器失败'
    }
    ElMessage.error(err.message)
    return Promise.reject(err.response)
  },
)

// 导出方法
export function get(url, params) {
  return http.get(url, { params })
}

export function post(url, data) {
  return http.post(url, data)
}
